<template>
  <div class="cropper-image">
    <div class="publishFrom_ box">
      <img v-if="selectFileOrNot" :src="previewImgURL" class="avatar">
      <div class="publishFrom_b" v-else>
        <i class="el-icon-upload"></i>
        <p>点击上传图片</p>
        <p>（仅支持jpg/jpeg/png图片格式）</p>
      </div>
      <uploader :options="uploadOptions" :autoStart="false" ref="uploader" :file-status-text="statusText" @file-added="fileAddImg" @file-removed="fileRemoved" @file-success="fileSuccess" @file-error="fileFail" class="uploader-example">
        <uploader-unsupport></uploader-unsupport>
        <uploader-btn :directory="false" :attrs="attrs" v-if="selectFileShow" :single="true"></uploader-btn>
        <!-- <uploader-list  v-if="!selectFileShow"></uploader-list> -->
        <div class="uploader-close-box" v-show="previewImgURL">
          <label class="el-upload-list__item-status-label" @click="fileRemoved">
            <transition name="el-fade-in-linear">
              <i class="el-icon-upload-success el-icon-check"></i>
            </transition>
            <transition name="el-fade-in-linear">
              <i class="el-icon-close"></i>
            </transition>
          </label>
        </div>
      </uploader>
    </div>

    <el-dialog title="图片设置" :visible.sync="cropperViews" width="1000px" custom-class="croppering" :close-on-click-modal="false">
      <div class="croppering">
        <div class="cropper">
          <vueCropper ref="cropper" :img="imgOption.img" :outputSize="imgOption.size" :outputType="imgOption.outputType" :info="true" :full="imgOption.full" :canMove="imgOption.canMove" :canMoveBox="imgOption.canMoveBox" :fixedBox="imgOption.fixedBox" :original="imgOption.original" :autoCrop="imgOption.autoCrop" :autoCropWidth="imgOption.autoCropWidth" :autoCropHeight="imgOption.autoCropHeight" :centerBox="imgOption.centerBox" :high="imgOption.high" :infoTrue="imgOption.infoTrue" :enlarge="imgOption.enlarge">
          </vueCropper>
        </div>
        <div slot="footer" class="dialog-footer cropper_btn">
          <el-button @click="clearFilet()">取消</el-button>
          <el-button type="primary" @click="finish('blob')">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { VueCropper } from 'vue-cropper';

export default {
  components: {
    VueCropper,
  },
  props: {

  },
  data() {
    return {
      // 选择图片：
      selectFileOrNot: false,  //是否选中文件
      previewImgURL: '',
      uploadOptions: {
        target: this.BASE_URL + '/api/resource/res_upload',
        testChunks: false,
        headers: { Authorization: `Bearer ` + this.$g.access_token },
      },
      uploadInfo: {//最后获取的文件大小
        file_name: '',
        file_path: '',
        file_size: 0
      },
      statusText: {
        success: '上传成功',
        error: '上传出错',
        uploading: '正在上传...',
        paused: '暂停',
        waiting: '等待上传'
      },
      imageType: ['image/jpeg', 'image/bmp', 'image/png'],  // 上传图片格式
      attrs: {
        accept: ['image/*']
      },
      selectFileShow: true,//是否显示选择文件按钮
      // 裁切图片：
      cropperViews: false, // 图片裁剪框，默认不显示
      imgOption: { // vue-cropper 参数配置
        img: '', // 裁剪图片的地址
        size: 1, // 裁剪生成图片的质量
        full: false, // 是否输出原图比例的截图
        // outputType: 'png', //输出图片格式
        canMove: true, //能否拖动图片
        fixedBox: true, //截图框固定大小
        original: false, //否显示原始宽高
        canMoveBox: true,  //能否拖动截图框
        autoCrop: true, //autoCrop 是否自动生成截图框
        // 只有自动截图开启 宽度高度才生效
        autoCropWidth: 290,
        autoCropHeight: 160,
        centerBox: false, //截图框是否限制在图片里
        high: true //是否根据dpr生成适合屏幕的高清图片
      },


    };
  },
  methods: {
    // 添加图片
    fileAddImg(file, fileList) {
      let file_type = file.fileType.toLocaleLowerCase();
      if (!this.imageType.includes(file_type)) {
        this.$message.warning('只允许上传 jpg/jpeg/png 格式图片')
      } else {
        this.imgOption.img = window.URL.createObjectURL(file.file)
        this.cropperViews = true;
      }
    },
    //移除图片
    fileRemoved(file) {
      this.previewImgURL = '';
      this.selectFileOrNot = false;
      this.selectFileShow = true;
    },
    //上传成功  
    fileSuccess(rootFile, file, message, chunk) {
      var mess = eval('(' + message + ')');
      mess = handleResponseData(mess);
      if (parseInt(mess.data.status) === 1) {
        this.uploadOrNot = true;
        this.uploadInfo.file_name = mess.data.file_name;
        this.uploadInfo.file_path = mess.data.file_path;
        this.uploadInfo.post_fix = mess.data.post_fix;
        this.$emit('picture', mess.data.file_path);//获取到的图片路径，传回父组件
        console.log(mess.data.file_path)
      }
    },
    // 上传失败
    fileFail(rootFile, file, message, chunk) {
      uploaderFileFail(this, this.$refs.uploader.uploader, file, message);
    },
    //清空上传控件列表的数据
    clearFilet() {
      this.cropperViews = false;
      this.$refs.uploader.uploader.fileList = [];
      this.$refs.uploader.uploader.files = [];
    },
    //图片裁剪后替换原图片，并把图片上传
    finish(type) {
      if (type === 'blob') {
        this.$refs.cropper.getCropBlob((data) => {
          if (data.size > 10240000) {
            this.$message.warning('只允许上传10M以内的图片');
            this.clearFilet();
          } else {
            this.$refs.uploader.uploader.fileList[0].file = data
            this.$refs.uploader.uploader.files[0].file = data
            this.$refs.uploader.uploader.fileList[0].size = data.size
            this.$refs.uploader.uploader.files[0].size = data.size;
            this.$refs.uploader.uploader.fileList[0].uniqueIdentifier = data.size + "-" + this.$refs.uploader.uploader.fileList[0].name;
            this.$refs.uploader.uploader.fileList[0].chunks[0].endByte = data.size;

            this.uploadInfo.file_size = data.size;
            this.previewImgURL = window.URL.createObjectURL(data);
            // console.log(data)
            this.fileUpload();
          }
        })
      } else if (type === 'base64') {
        this.$refs.cropper.getCropData((data) => {
          let modelView = dataURLtoFile(data, this.$refs.uploader.uploader.fileList[0].name);

          if (modelView.size > 10240000) {
            this.$message.warning('只允许上传10M以内的图片');
            this.clearFilet();
          } else {
            this.$refs.uploader.uploader.fileList[0].file = modelView
            this.$refs.uploader.uploader.files[0].file = modelView
            this.$refs.uploader.uploader.fileList[0].size = modelView.size
            this.$refs.uploader.uploader.files[0].size = modelView.size

            this.previewImgURL = data;
            this.uploadInfo.file_size = this.$refs.uploader.uploader.fileList[0].size;

            this.fileUpload();
          }
        })
      }
    },
    // 上传
    fileUpload() {
        // console.log(this.$refs.uploader.uploader)
      this.selectFileOrNot = true;
      this.selectFileShow = false;
      this.cropperViews = false;
      this.$refs.uploader.uploader.upload();
    },
  }
};
</script>

<style lang="scss">
// uploader
.publishFrom_ {
  width: 100%;
  height: 100%;
  border: 1px solid #ddd;
  position: relative;
  .avatar {
    width: 100%;
    height: 100%;
    object-fit: fill;
  }
  .el-upload--text {
    width: 100%;
    height: 100%;
  }
  .uploader {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.1);
  }
  .uploader-list {
    top: 45px;
  }
  .uploader-file {
    height: initial;
    line-height: initial;
    border: 0;
    border-radius: 100px;
  }
  .uploader-file-progress {
    background: #338efc;
  }
  .uploader-file-info {
    > div {
      display: inline-block;
      line-height: 20px;
      vertical-align: middle;
      width: auto;
      margin-right: 20px;
      text-align: center;
      float: initial;
      color: #666;
    }
    .uploader-file-name {
      display: block;
      width: 100%;
      margin: 0;
      margin-bottom: 15px;
      display: none;
    }
    span {
      margin-top: 0;
      &:last-of-type {
        margin: 0;
      }
    }
    .uploader-file-actions {
      margin: 0;
    }
  }
  .uploader-file-icon {
    margin: 0;
    margin-right: 10px;
  }
  .uploader-file-status,
  .uploader-file-size,
  .uploader-file-name {
    text-indent: 0;
  }
  .uploader-btn {
    display: block;
    position: relative;
    padding: 0;
    font-size: 100%;
    border: 0;
    background: none;
    height: 100%;
    line-height: 134px;
    text-align: center;
  }

  .uploader-close-box {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
    .el-upload-list__item-status-label {
      display: block;
      position: absolute;
      right: -17px;
      top: -7px;
      width: 46px;
      height: 26px;
      background: #13ce66;
      text-align: center;
      transform: rotate(45deg);
      box-shadow: 0 1px 1px #ccc;

      .el-icon-check {
        font-size: 12px;
        margin-top: 12px;
        color: #fff;
        transform: rotate(-45deg);
        font-family: "element-icons" !important;
        speak: none;
        font-style: normal;
        font-weight: normal;
        font-variant: normal;
        text-transform: none;
        line-height: 1;
        vertical-align: baseline;
        display: inline-block;
        -webkit-font-smoothing: antialiased;
      }

      .el-icon-check:before {
        content: "\E6DA";
      }

      .el-icon-close {
        display: none;
      }
    }
  }

  .uploader-close-box:hover {
    .el-upload-list__item-status-label {
      background: #f56c6c;
      box-shadow: none;
      cursor: pointer;

      .el-icon-check {
        display: none;
      }

      .el-icon-close {
        position: absolute;
        transform: rotate(-45deg);
        top: 10px;
        color: #fff;
        right: 14px;
        font-family: "element-icons" !important;
        speak: none;
        font-style: normal;
        font-weight: normal;
        font-variant: normal;
        text-transform: none;
        line-height: 1;
        vertical-align: baseline;
        display: inline-block;
        -webkit-font-smoothing: antialiased;
      }

      .el-icon-close:before {
        content: "\E6DB";
      }
    }
  }
}
.publishFrom_b {
  text-align: center;

  > i {
    font-size: 60px;
    color: #9cd1ff;
    margin-top: 10px;
  }

  i:before {
    content: "\E7C3";
  }

  > p {
    margin: 0;
    line-height: 20px;
    font-size: 12px;
    color: #999;
  }
}

// cropper
.croppering {
  .is-ai {
    overflow: hidden;
    margin-bottom: 40px;

    > .el-form-item {
      display: inline-block;
      vertical-align: top;
      &:nth-of-type(2) {
        float: right;
      }
    }
  }

  .cropper {
    height: 500px;

    > div {
      height: 100%;
    }
  }

  .dialog-footer {
    padding: 35px 0;
    text-align: center;

    button {
      padding: 10px 30px;
    }
  }

  .vue-cropper {
    position: relative;
    width: 100%;
    height: 500px;
    box-sizing: border-box;
    user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    direction: ltr;
    touch-action: none;
    text-align: left;
    background-image: url("");
  }

  .cropper-box,
  .cropper-box-canvas,
  .cropper-drag-box,
  .cropper-crop-box,
  .cropper-face {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    user-select: none;
  }

  .cropper-box-canvas img {
    position: relative;
    text-align: left;
    user-select: none;
    transform: none;
    max-width: none;
    max-height: none;
  }

  .cropper-box {
    overflow: hidden;
  }

  .cropper-move {
    cursor: move;
  }

  .cropper-crop {
    cursor: crosshair;
  }

  .cropper-modal {
    background: rgba(0, 0, 0, 0.5);
  }

  .cropper-view-box {
    display: block;
    overflow: hidden;
    width: 100%;
    height: 100%;
    outline: 1px solid #39f;
    outline-color: rgba(51, 153, 255, 0.75);
    user-select: none;
  }

  .cropper-view-box img {
    user-select: none;
    text-align: left;
    max-width: none;
    max-height: none;
  }

  .cropper-face {
    top: 0;
    left: 0;
    background-color: #fff;
    opacity: 0.1;
  }

  .crop-info {
    position: absolute;
    left: 0px;
    min-width: 65px;
    text-align: center;
    color: white;
    line-height: 20px;
    background-color: rgba(0, 0, 0, 0.8);
    font-size: 12px;
  }

  .crop-line {
    position: absolute;
    display: block;
    width: 100%;
    height: 100%;
    opacity: 0.1;
  }

  .line-w {
    top: -3px;
    left: 0;
    height: 5px;
    cursor: n-resize;
  }

  .line-a {
    top: 0;
    left: -3px;
    width: 5px;
    cursor: w-resize;
  }

  .line-s {
    bottom: -3px;
    left: 0;
    height: 5px;
    cursor: s-resize;
  }

  .line-d {
    top: 0;
    right: -3px;
    width: 5px;
    cursor: e-resize;
  }

  .crop-point {
    position: absolute;
    width: 8px;
    height: 8px;
    opacity: 0.75;
    background-color: #39f;
    border-radius: 100%;
  }

  .point1 {
    top: -4px;
    left: -4px;
    cursor: nw-resize;
  }

  .point2 {
    top: -5px;
    left: 50%;
    margin-left: -3px;
    cursor: n-resize;
  }

  .point3 {
    top: -4px;
    right: -4px;
    cursor: ne-resize;
  }

  .point4 {
    top: 50%;
    left: -4px;
    margin-top: -3px;
    cursor: w-resize;
  }

  .point5 {
    top: 50%;
    right: -4px;
    margin-top: -3px;
    cursor: e-resize;
  }

  .point6 {
    bottom: -5px;
    left: -4px;
    cursor: sw-resize;
  }

  .point7 {
    bottom: -5px;
    left: 50%;
    margin-left: -3px;
    cursor: s-resize;
  }

  .point8 {
    bottom: -5px;
    right: -4px;
    cursor: se-resize;
  }
}
</style>